package com.suxin.config;

import com.suxin.enums.BaseEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Tang
 * @classname MyBaseTypeHandler
 * @description [  ]
 * @date 2021/5/6 13:20
 */
public class MyBaseTypeHandler<E extends BaseEnum> extends BaseTypeHandler<E> {

    private Class enumClass;
    private E[] enums;

    public MyBaseTypeHandler(Class<E> enumClass) {
        this.enumClass = enumClass;
        enums = enumClass.getEnumConstants();
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, E e, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, e.getCode());
    }

    @Override
    public E getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if (resultSet.wasNull()) {
            return null;
        }
        return getEnumByCode(resultSet.getObject(s));
    }

    @Override
    public E getNullableResult(ResultSet resultSet, int i) throws SQLException {
        if (resultSet.wasNull()) {
            return null;
        }
        return getEnumByCode(resultSet.getObject(i));
    }

    @Override
    public E getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }

    private E getEnumByCode(Object code) {
        if (code instanceof Integer || code instanceof Short || code instanceof Long) {
            for (E e : enums) {
                if (code.equals(e.getCode())) {
                    return e;
                }
            }
        }
        if (code instanceof String) {
            for (E e : enums) {
                if (code.equals(e.getCode())) {
                    return e;
                }
            }
        }
        throw new IllegalArgumentException("参数转化异常!");
    }
}